package com.zhuss.timer;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 自动重启 plc 服务、socket 服务  每  8 分钟检测到服务未启动， 重启
 * @author Administrator
 *
 */

@Component
@Configuration  
@EnableScheduling
public class RestartSocketTask {
	
	private static Logger  LOGGER = LoggerFactory.getLogger(RestartSocketTask.class);
	
//	@Scheduled(cron = "0/10 * * * * ?")
	@Scheduled(cron = "0 0/8 * * * ?")
	private void configureTasks() {
		Boolean run1 = isRunning("tasklist /FI \"IMAGENAME eq NetServieAsync.exe\"", "NetServieAsync.exe");
		LOGGER.error("==================== NetServieAsync.exe===" + run1);
		String cmd1 ="D:\\java\\socket.bat";
		if (!run1) {
			restart(cmd1);
		}
		Boolean run2 = isRunning("tasklist /FI \"IMAGENAME eq SrcErp.exe", "SrcErp.exe");
		LOGGER.error("==================== SrcErp.exe===" + run2);
		String cmd2 ="D:\\java\\status.bat";
		if (!run2) {
			try {
				Thread.sleep(60000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			restart(cmd2);
		}
		// System.err.println("RestartSocketTask-------执行静态定时任务时间: " + LocalDateTime.now());
	}
	
	public static void main(String[] args) {
		System.out.println(isRunning("tasklist /FI \"IMAGENAME eq NetServieAsync.exe\"","NetServieAsync.exe"));
	}
	
	public void restart(String cmd) {
		Process obj = null;
         try {
        	Thread.sleep(1000);
            obj = Runtime.getRuntime().exec(cmd);
            int status = obj.waitFor();
            LOGGER.error("status: " + status);
            // LOGGER.error(JsonUtil.toJson(obj));
         } catch (Exception e) {
        	e.printStackTrace();
        	//LOGGER.error(JsonUtil.toJson(obj));
         }
	}


	public static boolean isRunning(String cmd, String processName) {
		BufferedReader bufferedReader = null;
		try {
			Process proc = Runtime.getRuntime().exec(cmd);
			bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
			String line = null;
			int i = 0;
			while ((line = bufferedReader.readLine()) != null) {
				LOGGER.info("===============" + ++i + ": " + line);
				if (line.contains(processName)) { //判断是否存在
					return true;
				}
			}
			return false;
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (Exception ex) {
					
				}
			}
		}
	}
}
